<template>
  <div class="warpper-box payOrder">
    <a-card>
      <a-row :gutter="20">
        <a-col :span="4">
          <a-card>
            <a-statistic title="公司社保合计" :value="statisticsInfo.companySocialTotalPay" :value-style="{ color: '#cf1322' }"  prefix="￥">
            </a-statistic>
          </a-card>
        </a-col>
        <a-col :span="4">
          <a-card>
            <a-statistic title="公司公积金合计" :value="statisticsInfo.companyFundsTotalPay" :value-style="{ color: '#cf1322' }"  prefix="￥">
            </a-statistic>
          </a-card>
        </a-col>
        <a-col :span="4">
          <a-card>
            <a-statistic title="个人社保合计" :value="statisticsInfo.personalSocialTotalPay" :value-style="{ color: '#cf1322' }" prefix="￥">
            </a-statistic>
          </a-card>
        </a-col>
        <a-col :span="4">
          <a-card>
            <a-statistic title="个人公积金合计" :value="statisticsInfo.personalFundsTotalPay" :value-style="{ color: '#cf1322' }" prefix="￥">
            </a-statistic>
          </a-card>
        </a-col>
        <a-col :span="4">
          <a-card>
            <a-statistic title="服务费合计" :value="statisticsInfo.serviceFee" :value-style="{ color: '#cf1322' }" prefix="￥">
            </a-statistic>
          </a-card>
        </a-col>
        <a-col :span="4">
          <a-card>
            <a-statistic title="总金额合计" :value="statisticsInfo.totalPay" :value-style="{ color: '#cf1322' }" prefix="￥">
            </a-statistic>
          </a-card>
        </a-col>
      </a-row>
    </a-card>
    <a-card style="margin-top: 10px;">
      <a-form layout="inline">
        <a-form-item label="员工姓名">
          <a-input placeholder="请输入员工姓名" v-model="params.insureStaffName"></a-input>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" icon="search" @click="addLoad()">搜索</a-button>
          <a-button type="primary" icon="setting" @click="reset()">重置</a-button>
          <a-button type="primary" @click="payOrderExport()">导出</a-button>
          <a-button type="warning" @click="importJoinVisible = true"
            v-if="orderStatus == 1 || orderType == 3">添加人员</a-button>
          <a-button type="warning" @click="importCustomVisible = true"
            v-if="orderStatus == 1 || orderType == 3">导入自定义费用</a-button>
        </a-form-item>
      </a-form>
      <a-table :columns="table.columns" :data-source="table.loadData" :pagination="table.pagination"
        @change="handleTableChange" rowKey="insureOrderStaffId" style="margin-top: 10px;" :scroll="{ x: 2600,y: 305 }">
        <!-- 操作栏-->
        <span slot="action" slot-scope="text, record">
          <!-- 编辑模块 | 字段 -->
          <a @click="$refs.createInfo.add(record)">编辑</a>
          <a-divider type="vertical" />
          <a-popconfirm title="确认删除?" ok-text="确认" cancel-text="取消" @confirm="remove(record)">
            <a>删除</a>
          </a-popconfirm>
        </span>
      </a-table>
      <div style="height: 25px;"></div>
    </a-card>
    <add-info ref="createInfo" @on-ok="addLoad"></add-info>
    <!-- 添加人员 -->
    <a-modal v-model="isAdd" title="选择员工" :confirmLoading="submitLoadingAdd" width="400px" ok-text="确认" cancel-text="取消"
      @ok="addSubmit">
      <a-tree v-if="treeData.length > 0" v-model="checkedKeys" :tree-data="treeData" :defaultExpandedKeys="expandedKeys"
        :replaceFields="{ title: 'orgName', key: 'orgId' }" checkable>
      </a-tree>
    </a-modal>
    <!-- 返回||提交 -->
    <a-card class="footBtn" hoverable :bordered="false">
      <a-button key="back" icon="logout" class="ant-btn-warning" @click="goBack">返回</a-button>
      <!-- <a-button type="primary" icon="file-done" @click="submit" style="margin-left: 10px;">提交</a-button> -->
    </a-card>
    <!-- 批量导入参保人员 -->
    <a-modal v-model="importJoinVisible" title="人员导入" width="540px" :footer="null">
      <a-alert message="第一步：下载人员录入模板；模版内已包含最新员工信息，请点击下载。" type="info" />
      <a-button type="primary" @click="downloadJoin" ghost style=";margin: 20px 0;width: 160px;">下载模板</a-button>
      <a-alert message="第二步：批量导入人员数据；请将填写完整的员工社保基数。" type="info" />
      <a-button type="primary" @click="importJoin" style="margin: 20px 0;width: 160px;">上传文件</a-button>
      <input type="file" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ref="fileJoinExcel"
        @change="importJoinHandle" style="display: none;" />
    </a-modal>
    <!-- 导入自定义费用 -->
    <a-modal v-model="importCustomVisible" title="导入自定义费用表单" width="540px" :footer="null">
      <a-alert message="第一步：下载人员信息模板模版内的表头请勿改动，防止导入时出错。" type="info" />
      <a-button type="primary" @click="downloadCustom" ghost style=";margin: 20px 0;width: 160px;">下载模板</a-button>
      <a-alert message="第二步：批量导入自定义数据，自定义数据无计算规则，请填写完整信息。" type="info" />
      <a-button type="primary" @click="importCustom" style="margin: 20px 0;width: 160px;">上传文件</a-button>
      <input type="file" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ref="fileCustomExcel"
        @change="importCustomHandle" style="display: none;" />
    </a-modal>
  </div>
</template>

<script>
import {
  COLUMNS_PAYORDERDETAIL
} from "./form"
import AddInfo from "./parOrderDetail_add.vue"
import {
  getTableDetailPage,
  deleteInsureOrderStaff,
  getOrderStaffInsureNo,
  insureOrderAddStaff,
  exportInsureOrderStaff,
  orderStaffExcelTemplate,
  downloadOrderStaffCustomFeeExcelTemplate,
  insureOrderStaffCustomFee,
  orderStatisticsInfo
} from "@/api/human/ensurePayOrder"
import {
  selectEnterpriseOrgTreeStaff
} from "@/api/human/ensureJoinStaff"
import { mapGetters, mapActions } from 'vuex'
export default {
  name: 'payOrderDetail',
  components: {
    AddInfo
  },
  data() {
    return {
      params: {
        insureOrderId: "",
        insureStaffName: ""
      },
      orderStatus: "",
      orderType: "",
      enterpriseId: "",
      table: {
        columns: COLUMNS_PAYORDERDETAIL,
        loadData: [],
        pagination: {
          current: 1,
          pageSize: 10,
          total: 0,
          showSizeChanger: true,
					showQuickJumper: true,
          pageSizeOptions: ["10", "20", "50", "100"],
          showTotal: total => `共有 ${total} 条数据`,
        }
      },
      pagination: { current: 1, pageSize: 10 },

      submitLoadingAdd: false,
      isAdd: false, // 添加人员开关
      treeData: [], // 人员列表
      checkedKeys: [],
      expandedKeys: [],
      importJoinVisible: false,
      importCustomVisible: false,

      statisticsInfo: {},

      selectedRowKeys: [], // 选择的table数据id
      selectedRows: [], // 选择的table数据
    }
  },
  filters: {

  },
  mounted() {
    window.addEventListener('keyup', this.keyDown);
  },
  destroyed() {
    window.removeEventListener('keyup', this.keyDown);
  },
  beforeCreate() {
    this.events_form = this.$form.createForm(this, {
      name: 'events_form'
    })
  },
  computed: {
    ...mapGetters(['userInfo']),
  },
  created() {

  },
  activated() {
    this.params.insureOrderId = this.$route.query.insureOrderId || "";
    this.orderStatus = this.$route.query.orderStatus || "";
    this.orderType = this.$route.query.orderType || "";
    this.enterpriseId = this.$route.query.enterpriseId || "";
    this.loadTable(true);
    this.getStatisticsInfo();
  },
  methods: {
    // table复选框选择
    onSelectChange(selectedRowKeys, selectedRows) {
      // console.log('selectedRowKeys changed: ', selectedRowKeys);
      this.selectedRowKeys = selectedRowKeys;
      this.selectedRows = selectedRows;
    },
    // 获取参保订单统计金额
    async getStatisticsInfo() {
      const { code, data } = await orderStatisticsInfo(this.params.insureOrderId);
      if (code === '1') {
        this.statisticsInfo = data;
      }
    },
    // 获取列表
    async loadTable(flag) {
      let params = this.params;
      if (this.orderStatus == 1 || this.orderType == 3) {
        this.table.columns = [
          {
            title: '姓名',
            dataIndex: 'insureStaffName',
						fixed: "left",
          },
          {
            title: '身份证号',
            dataIndex: 'idCard',
						fixed: "left",
          },
          {
            title: '参保方案',
            dataIndex: 'caseName',
						fixed: "left",
          },
          {
            title: '参保城市',
            dataIndex: 'city',
						fixed: "left",
          },
          {
            title: '个人养老',
            dataIndex: 'pensionPersonalPay',
          },
          {
            title: "公司养老",
            dataIndex: "pensionCompanyPay",
          },
          {
            title: '个人医疗',
            dataIndex: 'medicalPersonalPay',
          },
          {
            title: '公司医疗',
            dataIndex: 'medicalCompanyPay',
          },
          {
            title: '个人失业',
            dataIndex: 'loseJobPersonalPay',
          },
          {
            title: "公司失业",
            dataIndex: "loseJobCompanyPay",
          },
          // {
          //   title: '个人工伤',
          //   dataIndex: 'injuryPersonalPay',
          // },
          {
            title: '公司工伤',
            dataIndex: 'injuryCompanyPay',
          },
          // {
          //   title: '个人生育',
          //   dataIndex: 'birthPersonalPay'
          // },
          {
            title: '公司生育',
            dataIndex: 'birthCompanyPay'
          },
          {
            title: '个人大病',
            dataIndex: 'bigIllPersonalPay',
          },
          {
            title: '公司大病',
            dataIndex: 'bigIllCompanyPay',
          },
          {
            title: '个人公积金',
            dataIndex: 'fundsPersonalPay',
          },
          {
            title: "企业公积金",
            dataIndex: "fundsCompanyPay",
          },
          {
            title: '公司残保金',
            dataIndex: 'disabilityCompanyPay',
          },
          {
            title: "其他费用",
            dataIndex: "otherCompanyPay",
          },
          {
            title: '操作',
            dataIndex: 'action',
            fixed: "right",
            scopedSlots: { customRender: 'action' }
          },
        ]
      } else {
        this.table.columns = [
          {
            title: '姓名',
            dataIndex: 'insureStaffName',
						fixed: "left",
          },
          {
            title: '身份证号',
            dataIndex: 'idCard',
						fixed: "left",
          },
          {
            title: '参保方案',
            dataIndex: 'caseName',
						fixed: "left",
          },
          {
            title: '参保城市',
            dataIndex: 'city',
						fixed: "left",
          },
          {
            title: '个人养老',
            dataIndex: 'pensionPersonalPay',
          },
          {
            title: "公司养老",
            dataIndex: "pensionCompanyPay",
          },
          {
            title: '个人医疗',
            dataIndex: 'medicalPersonalPay',
          },
          {
            title: '公司医疗',
            dataIndex: 'medicalCompanyPay',
          },
          {
            title: '个人失业',
            dataIndex: 'loseJobPersonalPay',
          },
          {
            title: "公司失业",
            dataIndex: "loseJobCompanyPay",
          },
          // {
          //   title: '个人工伤',
          //   dataIndex: 'injuryPersonalPay',
          // },
          {
            title: '公司工伤',
            dataIndex: 'injuryCompanyPay',
          },
          // {
          //   title: '个人生育',
          //   dataIndex: 'birthPersonalPay'
          // },
          {
            title: '公司生育',
            dataIndex: 'birthCompanyPay'
          },
          {
            title: '个人大病',
            dataIndex: 'bigIllPersonalPay',
          },
          {
            title: '公司大病',
            dataIndex: 'bigIllCompanyPay',
          },
          {
            title: '个人公积金',
            dataIndex: 'fundsPersonalPay',
          },
          {
            title: "企业公积金",
            dataIndex: "fundsCompanyPay",
          },
          {
            title: '公司残保金',
            dataIndex: 'disabilityCompanyPay',
          },
          {
            title: "其他费用",
            dataIndex: "otherCompanyPay",
          }
        ]
      }
      if (flag) {
        this.table.pagination.current = 1;
        this.table.pagination.pageSize = 10;
      }
      params.pageNum = this.table.pagination.current;
      params.pageSize = this.table.pagination.pageSize;
      const { code, data } = await getTableDetailPage(params);
      if (code === '1') {
        this.table.loadData = data.content;
        this.table.pagination.total = data.total || 0;
      }
    },
    handleTableChange(pagination) {
      this.table.pagination.current = pagination.current;
      this.table.pagination.pageSize = pagination.pageSize;
      this.loadTable(false);
    },
    // 人员模板下载
    downloadJoin() {
      orderStaffExcelTemplate().then(res => {
        const blob = new Blob([res]);
        const fileName = '人员录入模板.xlsx';
        const elink = document.createElement('a'); // 创建a标签
        elink.download = fileName;
        elink.style.display = 'none';
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click(); // 点击下载
        URL.revokeObjectURL(elink.href); // 释放URL 对象
        document.body.removeChild(elink); // 释放标签
      })
    },
    // 导入人员表单
    importJoin() {
      this.$refs.fileJoinExcel.click();
    },
    importJoinHandle(e) {
      e.preventDefault();
      let _this = this;
      let file = e.target.files[0];
      if (file === undefined) {
        return;
      }
      if (file.name.indexOf('.xls') === -1) {
        _this.$message.error("只支持xlsx");
        e.target.value = "";
        return;
      }
      if (!(file.size / 1024 / 1024 < 20)) {
        _this.$message.error('模版大小不能超过 20MB!');
        e.target.value = "";
        return;
      }
      e.target.value = "";
      if (file) {
        let formData = new FormData();
        formData.append("insureOrderId", _this.params.insureOrderId);
        formData.append("file", file);
        insureOrderAddStaff(formData).then((res) => {
          if (res.code == 1) {
            _this.importJoinVisible = false;
            _this.$message.success('操作成功');
            _this.loadTable(true);
            _this.getStatisticsInfo();
          }
        })
      }
    },
    // 自定义费用模板下载
    downloadCustom() {
      downloadOrderStaffCustomFeeExcelTemplate().then(res => {
        const blob = new Blob([res]);
        const fileName = '自定义费用模板.xlsx';
        const elink = document.createElement('a'); // 创建a标签
        elink.download = fileName;
        elink.style.display = 'none';
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click(); // 点击下载
        URL.revokeObjectURL(elink.href); // 释放URL 对象
        document.body.removeChild(elink); // 释放标签
      })
    },
    // 导入人员表单
    importCustom() {
      this.$refs.fileCustomExcel.click();
    },
    importCustomHandle(e) {
      e.preventDefault();
      let _this = this;
      let file = e.target.files[0];
      if (file === undefined) {
        return;
      }
      if (file.name.indexOf('.xls') === -1) {
        _this.$message.error("只支持xlsx");
        e.target.value = "";
        return;
      }
      if (!(file.size / 1024 / 1024 < 20)) {
        _this.$message.error('模版大小不能超过 20MB!');
        e.target.value = "";
        return;
      }
      e.target.value = "";
      if (file) {
        let formData = new FormData();
        formData.append("insureOrderId", _this.params.insureOrderId);
        formData.append("file", file);
        insureOrderStaffCustomFee(formData).then((res) => {
          if (res.code == 1) {
            _this.importCustomVisible = false;
            _this.$message.success('操作成功');
            _this.loadTable(true);
            _this.getStatisticsInfo();
          }
        })
      }
    },
    // 删除订单
    async remove(row) {
      let params = {
        insureOrderStaffId: row.insureOrderStaffId,
      }
      const { code } = await deleteInsureOrderStaff(params)
      if (code == 1) {
        this.$message.success('操作成功');
        this.loadTable(true);
        this.getStatisticsInfo();
      }
    },
    // 导出参保订单
    payOrderExport() {
      exportInsureOrderStaff(this.params).then(res => {
        const blob = new Blob([res]);
        const fileName = '参保订单.xlsx';
        const elink = document.createElement('a'); // 创建a标签
        elink.download = fileName;
        elink.style.display = 'none';
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click(); // 点击下载
        URL.revokeObjectURL(elink.href); // 释放URL 对象
        document.body.removeChild(elink); // 释放标签
      })
    },
    // 打开添加参保人员
    openAdd() {
      this.isAdd = true;
      this.treeData = [];
      this.checkedKeys = [];
      this.expandedKeys = [];
      this.getStaffInfo();
    },
    // 获取已添加员工编号
    async getStaffInfo() {
      const { code, data } = await getOrderStaffInsureNo(this.params.insureOrderId);
      if (code === '1') {
        this.checkedKeys = data;
        this.expandedKeys = data;
        this.getTreeData();
      }
    },
    // 获取人员列表
    async getTreeData() {
      let params = {
        parentOrgId: this.enterpriseId,
        enterpriseId: this.enterpriseId,
        staffType: 2
      }
      const { code, data } = await selectEnterpriseOrgTreeStaff(params);
      if (code === '1') {
        if (this.checkedKeys.length == 0) {
          this.treeData = data;
        } else {
          this.treeData = this.formatData(data);
        }
      }
    },
    // 处理数据结构
    formatData(data) {
      data.forEach(tree => {
        let status = this.checkedKeys.indexOf(tree.orgId);
        if (status > -1) {
          tree.disableCheckbox = true;
        }
        if (tree.children.length > 0) {
          this.formatData(tree.children)
        }
      });
      return data;
    },
    // 添加人员提交
    async addSubmit() {
      if (this.checkedKeys.length == 0) {
        return this.$message.warning('请选择参保人员')
      }
      let param = {
        insureOrderId: this.params.insureOrderId,
        insureNoList: this.checkedKeys
      }
      this.submitLoadingAdd = true;
      const { code } = await insureOrderAddStaff(param);
      this.submitLoadingAdd = false;
      if (code == 1) {
        this.isAdd = false;
        this.$message.success('操作成功');
        this.loadTable(true);
        this.getStatisticsInfo();
      }
    },
    addLoad() {
      this.loadTable(true);
    },
    reset() {
      this.params.insureStaffName = "";
      this.loadTable(true);
      this.getStatisticsInfo();
    },
    goBack() {
      this.$router.back();
    }
  }
}
</script>
<style lang="less">
.payOrder {
  .ant-tabs-bar {
    margin-bottom: 5px;
  }
}
</style>